/*
 * CS_REQ_FAIRY_EGG_HATCH.cpp
 *
 *  Created on: 2013. 7. 22.
 *      Author: mega@gamevil.com
 */

#include "../../Command.h"
#include "../../User.h"
#include "../../NResource/Static.h"
#include "../../NUtil/Utils.h"
#include "../../NLogic/Item.h"
#include "../../NLogic/Bag.h"

namespace ProjectZ { namespace NCommand {

static void SendFailFairyEggHatch(User * pUser, int res)
{
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pAck << static_cast<int16_t>(res);
	pAck->MakePacket(CMD_SC_REQ_FAIRY_EGG_HATCH);
	pUser->Send(pAck);
}

void Command::CS_REQ_FAIRY_EGG_HATCH(User * pUser, ::Network::Packet * pPacket)
{
	PREPARE_PACKET;

	uint64_t eggSeq = 0;

	*pPacket >> eggSeq;

	NLogic::Bag * pBag = pUser->GetBag(BAG_TYPE_FAIRY);
	if (pBag == NULL)
	{
		DEBUGLOG("%s : pBag is NULL", __FUNCTION__);
		SendFailFairyEggHatch(pUser, ACK_UNKNOWN_ERROR);
		return;
	}

	NLogic::Item * pEgg = pBag->PopItem(eggSeq);
	if (pEgg == NULL)
	{
		DEBUGLOG("%s : pEgg is NULL! eggSeq=%lld", __FUNCTION__, eggSeq);
		SendFailFairyEggHatch(pUser, ACK_UNKNOWN_ERROR);
		return;
	}

	// 알 타입 확인
	// 0: 1성 ~ 3성
	// 1: 2성 ~ 7성
	// 2: 3성 ~ 7성
	int type = pEgg->GetData().eff_value[0];
	if (0 != type)
	{
		DEBUGLOG("%s : INVALID Type! eggSeq=%lld, type=%d", __FUNCTION__, eggSeq, type);
		pBag->AddItem(pEgg);
		SendFailFairyEggHatch(pUser, ACK_UNKNOWN_ERROR);
		return;
	}

	NLogic::Item::Data clsData;
	if (false == NResource::Static::InstancePtr()->GetFairyGachya()->FairyGachya(pUser, clsData, -1, type))
	{
		DEBUGLOG("%s : Egg Hatch Fail! eggSeq=%lld", __FUNCTION__, eggSeq);
		pBag->AddItem(pEgg);
		SendFailFairyEggHatch(pUser, ACK_UNKNOWN_ERROR);
		return;
	}

	bool bBagFull = false;
	NLogic::Item * pItem = pBag->AddItemWithData(clsData, bBagFull);
	if (NULL == pItem)
	{
		DEBUGLOG("%s : AddItem Fail! eggSeq=%lld", __FUNCTION__, eggSeq);
		pBag->AddItem(pEgg);
		SendFailFairyEggHatch(pUser, ACK_UNKNOWN_ERROR);
		return;
	}

	// 부화한 에그 삭제
	if (false == pEgg->DeleteDatabaseItemInfo(NLogic::Item::ItemStatus::EM_ITEM_STATUS_FAIRY_EGG_HATCH))
	{
		DEBUGLOG("%s : Database Update Fail! eggSeq=%lld", __FUNCTION__, eggSeq);
		SendFailFairyEggHatch(pUser, ACK_DB_ERROR);
		return;
	}

	// 응답
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pAck << static_cast<int16_t>(ACK_OK);
	*pAck << static_cast<uint8_t>(NUtil::GetEggGrade(pItem->GetData().quality));
	*pAck << pItem->GetItemSeq();
	pAck->MakePacket(CMD_SC_REQ_FAIRY_EGG_HATCH);
	pUser->Send(pAck);

}

} /*NCommand*/ } /*ProjectZ*/
